import { createRouter, createWebHashHistory } from 'vue-router'
import Layout from '@/layout/index.vue'
import Login from '@/views/loginAbout/login.vue'
import Register from '@/views/loginAbout/Register.vue'

const routes = [{
    path: '/',
    name: 'Home',
    component: Layout,
    redirect: 'login',
    children: [{
        path: 'login',
        name: 'Login',
        component: Login,
    },
    {
        path: 'register',
        name: 'Register',
        component: Register,
    },
    {
        path: '404',
        name: 'NotFound',
        component: () =>
            import('@/views/404.vue'),
    },
    {
        path: 'personal',
        name: 'Personal',
        meta: {
            requireAuth: true,
        },
        component: () =>
            import('@/views/personal/index.vue'),
        children: [{
            path: 'message',
            name: 'PersonMessage',
            component: () =>
                import('@/views/personal/Message.vue'),
        },],
    },
    {
        path: 'app',
        name: 'App',
        component: () =>
            import('@/views/app/index.vue'),
        children: [{
            path: 'user',
            name: 'User',
            component: () =>
                import('@/views/app/User.vue'),
        }, {
            path: 'dept',
            name: 'Dept',
            component: () =>
                import('@/views/app/Dept.vue'),
        }, {
            path: 'role',
            name: 'Role',
            component: () =>
                import('@/views/app/Role.vue'),
        }, {
            path: 'resource',
            name: 'Resource',
            component: () =>
                import('@/views/app/Resource.vue'),
        },],
    }, {
        path: 'sys/user',
        name: 'SysUser',
        component: () =>
            import('@/views/sys/User.vue'),
    }
    ],
},
{
    // vue router遵循最长匹配原则，所以不影响正常路由的使用
    path: '/:cathchAll(.*)',
    name: '404',
    component: () =>
        import('@/views/404.vue'),
},
]

const router = createRouter({
    history: createWebHashHistory(process.env.BASE_URL),
    routes,
})

router.beforeEach((to, from) => {
    const token = localStorage.getItem('token')
    if (to.meta.requireAuth && !token) {
        // 需要登陆的页面和没有token
        return { name: 'Login' }
    }
    return true
})
export default router